<!--Login module-->

<?php
	include 'dbc.php';
	session_start(); 
	
	if(isset($_SESSION['loggedin'])){
		header("Refresh: 1;url=main.php");
    	die("You have already logged in!");
	}
	
	if(isset($_POST['login'])){
		//The function mysql_real_escape_string() stops hackers!
		//$email is the email obtained from $_POST array
		//$password is the password obtained from $_POST array
   		$email = mysql_real_escape_string($_POST['email']);
   		$password = mysql_real_escape_string($_POST['password']); 
   		$e_password = md5($password);
		
		$check_login = "SELECT * FROM restaurant WHERE email = '$email' AND password = '$e_password' AND is_blocked='0' ";
		$result = mysql_query($check_login);
		
		// Fail to login
		if(mysql_num_rows($result) < 1){
     		echo "Password or username was incorrect!<br>";
			include 'login_horizontal.php';
			die();
   		}
		
		// Can login
		$userdata = mysql_fetch_array($result);
		//Store user data into session array
		$_SESSION['id'] = $userdata['id'];
		$_SESSION['is_admin'] = $userdata['is_admin'];
		$_SESSION['email'] = $userdata['email'];
		$_SESSION['name'] = $userdata['name'];
		$_SESSION['is_blocked'] = $userdata['is_blocked'];
		$_SESSION['loggedin'] = "YES";
		
		//Update last login time
		$user_id = $userdata['id'];
		$current_time = date ("Y-m-d H:i:s");
		$update_last_login = "UPDATE restaurant SET last_login='$current_time' WHERE id='$user_id'";
		mysql_query($update_last_login);
		
		//Auto redirect
		header("Refresh: 1;url=main.php");
   		die("Click <a href='main.php'>here</a> if your browser cannot redirect");
	}
	
	include 'login_horizontal.php';
	die();
?>
